package com.exmaple.MysqlMasterAndSlave;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Liuqz
 * @date 2018/12/22 15:30
 */
public class DynamicDataSoucreHolder {

    private static Logger logger = LoggerFactory.getLogger(DynamicDataSoucreHolder.class);

    private static ThreadLocal<String> contextHolder = new ThreadLocal<>();

    public static final String DB_MASTER = "master";

    public static final String DB_SLAVE = "slave";

    public static String getDbType() {
        String db = contextHolder.get();
        if (db == null) {
            db = DB_MASTER;
        }
        return db;
    }

    /**
     * 设置线程的dbType
     * @param string
     */
    public static void setDbType(String string) {
        logger.debug("使用数据源: " + string);
        contextHolder.set(string);
    }

    /**
     * 清理连接类型
     */
    public static void clearDBType() {
        contextHolder.remove();
    }
}
